package dao;

import anno.Component;
import pojo.Question;
import utils.JDBCUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 题目DAO实现类
 */
@Component
public class QuestionDao extends AbstractBaseDao<Question> {
    
    /**
     * 分页查询题目列表
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @param keyword 搜索关键词(题目内容)
     * @return 题目列表
     */
    public List<Question> findPage(int pageNum, int pageSize, String keyword) throws SQLException {
        return executeWithConnection(() -> {
            StringBuilder sql = new StringBuilder("SELECT * FROM " + tableName);
            List<Object> params = new ArrayList<>();
            
            // 添加搜索条件
            if (keyword != null && !keyword.trim().isEmpty()) {
                sql.append(" WHERE title LIKE ?");
                params.add("%" + keyword.trim() + "%");
            }
            
            // 添加分页
            sql.append(" LIMIT ?, ?");
            params.add((pageNum - 1) * pageSize);
            params.add(pageSize);
            
            ResultSet rs = (ResultSet) JDBCUtils.execute(sql.toString(), params.toArray());
            List<Question> results = new ArrayList<>();
            while (rs.next()) {
                results.add(mapResultSetToEntity(rs));
            }
            return results;
        });
    }
    
    /**
     * 统计符合条件的总记录数
     */
    public long countByKeyword(String keyword) throws SQLException {
        return executeWithConnection(() -> {
            StringBuilder sql = new StringBuilder("SELECT COUNT(*) FROM " + tableName);
            List<Object> params = new ArrayList<>();
            
            if (keyword != null && !keyword.trim().isEmpty()) {
                sql.append(" WHERE title LIKE ?");
                params.add("%" + keyword.trim() + "%");
            }
            
            ResultSet rs = (ResultSet) JDBCUtils.execute(sql.toString(), params.toArray());
            return rs.next() ? rs.getLong(1) : 0;
        });
    }

    /**
     * 根据ID列表批量查询题目
     *
     * @param ids 题目ID列表
     * @return 题目列表
     */
    public List<Question> findByIds(List<Integer> ids) throws SQLException {
        if (ids == null || ids.isEmpty()) {
            return Collections.emptyList();
        }
        return executeWithConnection(() -> {
            String sql = "SELECT * FROM " + tableName + " WHERE question_id IN (" +
                    ids.stream().map(id -> "?").collect(Collectors.joining(",")) + ")";
            List<Object> params = new ArrayList<>(ids);

            ResultSet rs = (ResultSet) JDBCUtils.execute(sql, params.toArray());
            List<Question> results = new ArrayList<>();
            while (rs.next()) {
                results.add(mapResultSetToEntity(rs));
            }
            return results;
        });
    }
}